package com.example.mybatisplusdemo.service;

import com.example.mybatisplusdemo.model.domain.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserProfileAnalysisService {
    private final ObjectMapper objectMapper;

    public void analyzeUserProfile(User user) {
        List<String> tags = new ArrayList<>();

        // 1. 分析出行偏好
        analyzeTravelPreferences(user, tags);

        // 2. 分析消费习惯
        analyzeConsumptionHabits(user, tags);

        // 3. 分析旅行历史
        analyzeTravelHistory(user, tags);

        // 4. 分析基本属性
        analyzeBasicAttributes(user, tags);

        // 5. 保存用户标签
        try {
            user.setUserTags(objectMapper.writeValueAsString(tags));
        } catch (JsonProcessingException e) {
            // 处理异常
        }
    }

    private void analyzeTravelPreferences(User user, List<String> tags) {
        Map<String, String> preferences = parseJsonToMap(user.getPreferences());
        String seatPreference = preferences.getOrDefault("seat_preference", "");
        if (!seatPreference.isEmpty()) {
            tags.add(seatPreference + "_座位偏好");
        }

        String mealPreference = preferences.getOrDefault("meal_preference", "");
        if (!mealPreference.isEmpty()) {
            tags.add(mealPreference + "_餐食偏好");
        }

        if (user.getPreferredDepartureTime() != null) {
            tags.add(user.getPreferredDepartureTime() + "_出发偏好");
        }

        if (user.getPreferredAirline() != null) {
            tags.add(user.getPreferredAirline() + "_偏好");
        }
    }

    private void analyzeConsumptionHabits(User user, List<String> tags) {
        if (user.getPreferredPriceRange() != null) {
            tags.add(user.getPreferredPriceRange() + "_消费水平");
        }

        List<String> favoriteAirports = parseJsonToList(user.getFavoriteAirports());
        if (!favoriteAirports.isEmpty()) {
            tags.add(favoriteAirports.size() + "_个收藏机场");
            tags.add(favoriteAirports.get(0) + "_常去目的地");
        }
    }

    private void analyzeTravelHistory(User user, List<String> tags) {
        List<String> travelHistory = parseJsonToList(user.getTravelHistory());
        if (!travelHistory.isEmpty()) {
            tags.add(travelHistory.size() + "_次历史航班");

            Map<String, Long> routeCounts = travelHistory.stream()
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

            String mostFrequentRoute = routeCounts.entrySet().stream()
                    .max(Map.Entry.comparingByValue())
                    .map(Map.Entry::getKey)
                    .orElse("");

            if (!mostFrequentRoute.isEmpty()) {
                tags.add(mostFrequentRoute.replace("-", "_") + "_热门航线");
            }

            Set<String> destinations = new HashSet<>();
            for (String route : travelHistory) {
                String[] parts = route.split("-");
                if (parts.length > 1) {
                    destinations.add(parts[1]);
                }
            }
            tags.add(destinations.size() + "_个独特目的地");
        }
    }

    private void analyzeBasicAttributes(User user, List<String> tags) {
        if (user.getAge() != null) {
            if (user.getAge() < 18) tags.add("青少年");
            else if (user.getAge() < 30) tags.add("青年");
            else if (user.getAge() < 50) tags.add("中年");
            else tags.add("老年");
        }

        if (user.getGender() != null) {
            tags.add(user.getGender().equals("男") ? "男性" : "女性");
        }
    }

    private Map<String, String> parseJsonToMap(String json) {
        try {
            if (json == null || json.isEmpty()) return new HashMap<>();
            return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});
        } catch (JsonProcessingException e) {
            return new HashMap<>();
        }
    }

    private List<String> parseJsonToList(String json) {
        try {
            if (json == null || json.isEmpty()) return new ArrayList<>();
            return objectMapper.readValue(json, new TypeReference<List<String>>() {});
        } catch (JsonProcessingException e) {
            return new ArrayList<>();
        }
    }
}